//
//  UITableView+Extension.swift
//  YangFoundation
//
//  Created by yuyang on 2021/12/21.
//

import UIKit

extension UITableView {

    /// 获取tableview当前内容高度(仅限于一个section)
    public func contentHeight() -> CGFloat {
        if self.numberOfRows(inSection: 0) == 0 {
            return 0
        }
        let lastCellRect = self.rectForRow(at: IndexPath(row: self.numberOfRows(inSection: 0) - 1, section: 0))
        let contentHeight = lastCellRect.origin.y + lastCellRect.size.height
        return contentHeight
    }
}

// MARK: - UITableView register and dequeue reuse
public extension UITableView {

    /// UITableView cell register
    ///
    /// - Parameters:
    ///   - cellClass: UITableViewCell class
    func register<T: UITableViewCell>(_ cellClass: T.Type) {
        let name = String(describing: cellClass)
        self.register(cellClass, forCellReuseIdentifier: name)
    }

    /// UITableView reusable cell dequeue
    ///
    /// - Parameters:
    ///   - cellClass: UITableViewCell class
    /// - Return: cell
    func dequeueReusableCell<T: UITableViewCell>(withCellClass cellClass: T.Type) -> T {
        let name = String(describing: cellClass)
        let cell = dequeueReusableCell(withIdentifier: name) as! T
        return cell
    }

    /// UITableView headerView / footerView register
    ///
    /// - Parameters:
    ///   - viewClass: viewClass
    func registerHeaderFooterViewClass<T: UITableViewHeaderFooterView>(_ viewClass: T.Type) {
        let name = String(describing: viewClass)
        self.register(viewClass, forHeaderFooterViewReuseIdentifier: name)
    }

    /// UITableView reusable headerView / footerView dequeue
    ///
    /// - Parameters:
    ///   - viewClass: viewClass
    /// - Return: headerView / footerView
    func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withViewClass viewClass: T.Type) -> T {
        let name = String(describing: viewClass)
        let view = dequeueReusableHeaderFooterView(withIdentifier: name) as! T
        return view
    }
}
